<template>
  <div class="wrapper">
    <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="用户真实名称" prop="realName">
        <el-input v-model="form.realName"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="form.tags"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择所属角色">
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <div class="btn">
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "UserAdd",
  data: function () {
    return {
      form: {
        name: '',
        realName: '',
        tags: '',
        roleId: ''
      },
      roles: [],
      formRules: {
        name: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: (rule,value,callback)=>{
              let reg= /^[0-9A-Za-z]+[.]*[0-9A-Za-z]*$/
              if(!reg.test(value)){callback(new Error('帐号必须是数字和字母的组合'))
              }else if(value.length < 4 || value.length > 20){
                callback(new Error('帐号必须是4-20位字母或数字'))
              }else{
                callback()
              }
            }, trigger: 'blur'}
        ],
        roleId: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    onSubmit(){
      this.$refs['form'].validate((valid)=> {
        if(valid){
          this.add()
          this.$alert('创建成功,默认密码为 qweASD!@#', '创建成功', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'success',
                message: `创建成功`
              });
              this.$router.push('/userManage')
            }
          });
        }else {
          return false;
        }
      })
    },
    add() {
      this.$http.post('/api/user/add', this.form)
    },
    async getAllRole() {
      let res = await this.$http.get("/api/role/getAllRole")
      this.roles = res.data
    }
  },
  created() {
    this.getAllRole()
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  width: 60%;
}
.btn {
  text-align: right;
}
</style>
